package com.estar.platform.caseInfo.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import com.estar.jinyou.entity.TmblEvalassistinfoEntity;
import com.estar.jinyou.entity.TmblEvallossinfoEntity;
import com.estar.jinyou.entity.TmblEvalpartinfoEntity;
import com.estar.jinyou.entity.TmblEvalrepairinfoEntity;
import com.estar.platform.caseInfo.entity.TmblCarInfoEntity;
import com.estar.platform.caseInfo.entity.TmblPicInfoEntity;
import com.estar.platform.caseInfo.entity.TmblSurveyInfoEntity;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.Table;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

@Component("jinYouEval")
@Scope("prototype")
public class jinYouEval {
	@Autowired
	private SystemService systemService;
	
	private static final Logger logger = Logger.getLogger(jinYouEval.class);
	private SimpleDateFormat ym = new SimpleDateFormat("yyyy-MM");
	private DecimalFormat myformat = new DecimalFormat();
	private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	

	@RequestMapping(params = "downPdf2")
	public String downPdf2(HttpServletRequest request, HttpServletResponse response,String  reportNo,String indexName){
		InputStream fis = null;
		OutputStream toClient = null;
		String pdfPath = null;
		try{
			request.setCharacterEncoding("utf-8");
			
			/*获取打印信息*/
			/*基本信息*/
			CriteriaQuery cq = new CriteriaQuery(TmblCarInfoEntity.class);
			cq.eq("reportNo", reportNo);
			cq.eq("indexNme", indexName);
			cq.add();
			List<TmblCarInfoEntity> carList=this.systemService.getListByCriteriaQuery(cq, false);
			
			/*end==基本信息*/
			
			/*车辆基本信息 和 修理厂信息*/
			CriteriaQuery cq2 = new CriteriaQuery(TmblEvallossinfoEntity.class);
			cq2.eq("report", reportNo);
			cq2.eq("carindex", indexName);
			cq2.add();
			List<TmblEvallossinfoEntity> list=this.systemService.getListByCriteriaQuery(cq2, false);
			
			/*end======车辆基本信息 和 修理厂信息*/
			
			/*配件信息*/
			CriteriaQuery cq3 = new CriteriaQuery(TmblEvalpartinfoEntity.class);
			cq3.eq("report", reportNo);
			cq3.eq("carindex", indexName);
			cq3.add();
			List<TmblEvalpartinfoEntity> partList=this.systemService.getListByCriteriaQuery(cq3, false);
			
			/*end=====配件信息*/
			
			/*工时信息*/
			CriteriaQuery cq4 = new CriteriaQuery(TmblEvalrepairinfoEntity.class);
			cq4.eq("report", reportNo);
			cq4.eq("carindex", indexName);
			cq4.add();
			List<TmblEvalrepairinfoEntity> repairList=this.systemService.getListByCriteriaQuery(cq4, false);
			
			/*end=====工时信息*/
			
			/*辅料信息*/
			CriteriaQuery cq5 = new CriteriaQuery(TmblEvalassistinfoEntity.class);
			cq5.eq("report", reportNo);
			cq5.eq("carindex", indexName);
			cq5.add();
			List<TmblEvalassistinfoEntity> assisList=this.systemService.getListByCriteriaQuery(cq5, false);
			/*end===辅料信息*/
			
			/*end=====================获取打印信息*/
			
			//生成文件
			String classLocalPath = this.getClass().getClassLoader().getResource("").getPath();
			classLocalPath = classLocalPath.replaceAll("%20", " ");
			classLocalPath = classLocalPath.substring(0, classLocalPath.indexOf("WEB-INF"));
			
			SimpleDateFormat sdflocal = new SimpleDateFormat("yyyyMMdd");
			//加一个日期分类
			TmblPicInfoEntity pic=new TmblPicInfoEntity();
			CriteriaQuery cqp=new CriteriaQuery(TmblPicInfoEntity.class);
			cqp.eq("imageCaseCode", reportNo);
			cqp.isNotNull("imageVhlNO");
			cqp.add();
			List<TmblPicInfoEntity> picList2= systemService.getListByCriteriaQuery(cqp, false);
			String url="201606/";
			if(picList2!=null && picList2.size()>0){
				pic=picList2.get(0);
				if(StringUtil.isNotEmpty(pic.getImgPath())){
					url=pic.getImgPath();
					url=url.substring(0, url.indexOf("KCLP"));//==appPicture/201706/
				}
			}
			
			String filePath =  classLocalPath + url + reportNo  ;
			
			File f=new File(filePath);
			if (!f.exists()) {
				f.mkdirs();//创建文件
			}
			pdfPath = makePdf2(carList,list,partList,repairList,assisList,filePath,request,response);
			
			
			
		}catch(Exception e){
			logger.error("打印错误:",e);
		}finally {
			
				try {
					if(fis!=null){
					fis.close();
					}
					if(toClient!=null){
						toClient.close();
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
		}
		return pdfPath;
		
	}

	
	/*打印内容*/
	private String makePdf2(List<TmblCarInfoEntity> carList, List<TmblEvallossinfoEntity> list,
			List<TmblEvalpartinfoEntity> partList, List<TmblEvalrepairinfoEntity> repairList,
			List<TmblEvalassistinfoEntity> assisList, String path, HttpServletRequest request,
			HttpServletResponse response) {
		OutputStream toClient = null;
		InputStream fis = null;
		String filePath = null;
		PdfWriter writer =null;
		try {
			/*获取数据*/
			TmblCarInfoEntity carInfoEntity=carList.get(0);
			TmblEvallossinfoEntity evallossinfoEntity=list.get(0);
			//
			String classLocalPath = this.getClass().getClassLoader().getResource("").getPath();
			classLocalPath = classLocalPath.replaceAll("%20", " ");
			classLocalPath = classLocalPath.substring(0, classLocalPath.indexOf("WEB-INF"));
			
			//字体
			String fontPath = classLocalPath + "caseInfoPdf/font/SIMSUN.TTC,1";
			//设置字体路径
			BaseFont bf = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H,BaseFont.EMBEDDED);
			
			Font titleFont = new Font(bf, 17);
			Font typeFont = new Font(bf, 13, Font.BOLD);//分类大标题
			Font textFont = new Font(bf, 12);// 正文字体数值;
			Font tipsFont = new Font(bf, 9);//签名
			Font signFont1 = new Font(bf, 13,Font.BOLD);////分类小标题
			Font textFont2 = new Font(bf, 13);//
			Font textFont3 = new Font(bf, 13);//字多变小
			Font textFont4 = new Font(bf, 13);//同保方案
			Document document  = new Document(PageSize.A4);
			//页边空白  
			document.setMargins(4, 4, 4, 4); 
			filePath=path+ "/"+carInfoEntity.getCarNo()+"的定损协议书"+".pdf";
			if (new File(filePath).exists()) {
				new File(filePath).delete();
			}
			writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
			
			
			// 3.打开文档
			document.open();
			//构造表格
		     Table table = new Table(4);
		     table.setBorder(Rectangle.NO_BORDER);
		     int hws[] = {16, 17, 16, 17};
		     table.setWidths(hws);
		     table.setWidth(95);
		     table.setPadding(3);
		     
		     //表头信息
		     Cell cellmain4 = new Cell(new Phrase("广东轻微交通事故损害赔偿定损协议书",titleFont));
		     cellmain4.setHorizontalAlignment(Element.ALIGN_CENTER);
		     cellmain4.setColspan(4);
		     cellmain4.setBorder(Rectangle.NO_BORDER);
		     table.addCell(cellmain4);
		     
		    
		     table.addCell(getCell("一、基本信息 ",typeFont));
		     table.addCell(new Phrase("案件流水号",textFont2));
		     table.addCell(new Phrase(carInfoEntity.getReportNo(),textFont2));
		     table.addCell(new Phrase("车牌号",textFont2));
		     table.addCell(new Phrase(carInfoEntity.getCarNo(),textFont2));
		     
		     table.addCell(new Phrase("驾驶员",textFont2));
		     table.addCell(new Phrase(carInfoEntity.getDriverNme(),textFont2));
		     table.addCell(new Phrase("联系电话",textFont3));
		     table.addCell(new Phrase(carInfoEntity.getPhone(),textFont2));
		     
		     table.addCell(new Phrase("车辆种类",textFont3));
		     table.addCell(new Phrase(carInfoEntity.getIndexNme(),textFont2));
		     table.addCell(getCellEmty(textFont));
		     
		    /* ===========================*/
		     table.addCell(getCell("车辆基本信息 ",typeFont));
		     table.addCell(new Phrase("车辆品牌",textFont2));
		     table.addCell(new Phrase(evallossinfoEntity.getVehbrandname(),textFont2));
		     table.addCell(new Phrase("车系",textFont2));
		     table.addCell(new Phrase(evallossinfoEntity.getVehseriname(),textFont2));
		     
		     table.addCell(new Phrase("车组",textFont2));
		     table.addCell(new Phrase(evallossinfoEntity.getVehgroupname(),textFont2));
		     table.addCell(new Phrase("车型",textFont3));
		     table.addCell(new Phrase(evallossinfoEntity.getVehyeartype(),textFont2));
		     
		     table.addCell(new Phrase("厂家名称",textFont3));
		     table.addCell(new Phrase(evallossinfoEntity.getVehfactoryname(),textFont2));
		     table.addCell(getCellEmty(textFont));
		     /*====================================*/
		     table.addCell(getCell("修理厂信息 ",typeFont));
		     table.addCell(new Phrase("修理厂名称",textFont2));
		     table.addCell(new Phrase(evallossinfoEntity.getRepairkindname(),textFont2));
		     table.addCell(new Phrase("所属区域",textFont2));
		     table.addCell(new Phrase(evallossinfoEntity.getQyzdname(),textFont2));
		     
		     table.addCell(new Phrase("系数（工时）",textFont3));
		     table.addCell(new Phrase(evallossinfoEntity.getFactorydict(),textFont2));
		     table.addCell(getCellEmty(textFont2));
		     
		     /*====================================*/
		     table.addCell(getCell("配件信息 ",typeFont));
		     
		     table.addCell(new Phrase("换件名称",textFont2));
		     table.addCell(new Phrase("单价",textFont2));
		     table.addCell(new Phrase("数量",textFont2));
		     table.addCell(new Phrase("小计",textFont2));
		   
		    	 for(TmblEvalpartinfoEntity partInfo:partList){
				     table.addCell(new Phrase(partInfo.getPartstandard(),textFont2));
					 table.addCell(new Phrase(monenyFom(partInfo.getLossprice())+"元",textFont2));
					 table.addCell(new Phrase(partInfo.getLosscount().toString(),textFont2));
					 table.addCell(new Phrase(monenyFom(partInfo.getSumprice())+"元",textFont2));
			     }
		    /* if (partList.size()>0 && partList!=null) {*/
			/*}else{
				table.addCell(new Phrase("无",textFont2));
				 table.addCell(new Phrase(monenyFom(new BigDecimal("0.00"))+"元",textFont2));
				 table.addCell(new Phrase("无",textFont2));
				 table.addCell(new Phrase(monenyFom(new BigDecimal("0.00"))+"元",textFont2));
			}
		     */
		     
		     /*====================================*/
		    
		     /*====================================*/
		     table.addCell(getCell("工时信息 ",typeFont));
		     
		     table.addCell(new Phrase("修理名称",textFont2));
		     table.addCell(new Phrase("工种",textFont2));
		     table.addCell(new Phrase("工时费",textFont2));
		     table.addCell(new Phrase("小计",textFont2));
		     
		    
		    	 for(TmblEvalrepairinfoEntity reInfo:repairList){
				     table.addCell(new Phrase(reInfo.getRepairitemname(),textFont2));
					 table.addCell(new Phrase(reInfo.getRepairname(),textFont2));
					 table.addCell(new Phrase(monenyFom(reInfo.getUnitmanhourprice())+"元",textFont2));
					 table.addCell(new Phrase(monenyFom(reInfo.repairfee)+"元",textFont2));
			     }
		    	 
		    	 /*if (repairList!=null && repairList.size()>0) {*/
			/*}else{
				table.addCell(new Phrase("无",textFont2));
				table.addCell(new Phrase("无",textFont2));
				 table.addCell(new Phrase(monenyFom(new BigDecimal("0.00"))+"元",textFont2));
				 table.addCell(new Phrase(monenyFom(new BigDecimal("0.00"))+"元",textFont2));
			}*/
		    
		     
		     /*====================================*/
		     
		     /*====================================*/
		     table.addCell(getCell("辅料信息 ",typeFont));
		     
		     table.addCell(new Phrase("辅料名称",textFont2));
		     table.addCell(new Phrase("单价",textFont2));
		     table.addCell(new Phrase("数量",textFont2));
		     table.addCell(new Phrase("小计",textFont2));
		    
		    	 for(TmblEvalassistinfoEntity asInfo:assisList){
				     table.addCell(new Phrase(asInfo.getMaterialname(),textFont2));
					 table.addCell(new Phrase(monenyFom(asInfo.getUnitprice())+"元",textFont2));
					 table.addCell(new Phrase(asInfo.getCount().toString(),textFont2));
					 table.addCell(new Phrase(monenyFom(asInfo.getMaterialfee())+"元",textFont2));
			     }
		    /* if (assisList!=null && assisList.size()>0) {*/
			/*}else{
				table.addCell(new Phrase("无",textFont2));
				 table.addCell(new Phrase(monenyFom(new BigDecimal("0.00"))+"元",textFont2));
				 table.addCell(new Phrase("无",textFont2));
				 table.addCell(new Phrase(monenyFom(new BigDecimal("0.00"))+"元",textFont2));
			}*/
		     
		     
		     /*====================================*/
		     table.addCell(getCell("合计信息 ",typeFont));
		     
		     table.addCell(new Phrase("配件合计",textFont2));
		     table.addCell(new Phrase(monenyFom(evallossinfoEntity.getSumchgcompfee())+"元",textFont2));
		     table.addCell(new Phrase("工时合计",textFont2));
		     table.addCell(new Phrase(monenyFom(evallossinfoEntity.getSumrepairfee())+"元",textFont2));
		     
		     table.addCell(new Phrase("辅料合计",textFont2));
		     table.addCell(new Phrase(monenyFom(evallossinfoEntity.getSummaterialfee())+"元",textFont2));
		     table.addCell(new Phrase("残值合计",textFont2));
		     table.addCell(new Phrase(monenyFom(evallossinfoEntity.getSumRemnant())+"元",textFont2));
		     
		     table.addCell(new Phrase("定损合计",textFont2));
		     table.addCell(new Phrase(monenyFom(evallossinfoEntity.getSumlossfee())+"元",textFont2));
		     table.addCell(getCellEmty(textFont));
		     
		     table.addCell(new Phrase("备注",textFont2));
		     Cell cellleft22= new Cell(new Phrase(evallossinfoEntity.getRemark(),textFont2));
		     cellleft22.setColspan(3);
		     cellleft22.setHorizontalAlignment(Element.ALIGN_LEFT);
		     table.addCell(cellleft22);
		     
		     CriteriaQuery cq = new CriteriaQuery(TmblSurveyInfoEntity.class);
				cq.eq("reportNo", carInfoEntity.getReportNo());
				cq.add();
				TmblSurveyInfoEntity surveyInfo = (TmblSurveyInfoEntity) systemService.getListByCriteriaQuery(cq, false).get(0);

		     String name="经办人："+surveyInfo.getAppUser().getEmpName();
		     Cell cellmain3 = new Cell(new Phrase(name,textFont));
		     cellmain3.setHorizontalAlignment(Element.ALIGN_RIGHT);
		     cellmain3.setColspan(4);
		     cellmain3.setBorder(Rectangle.NO_BORDER);
		     table.addCell(cellmain3);
		     
		     String tele="联系电话："+surveyInfo.getAppUser().getPhoneNo();
		     Cell cellmain5 = new Cell(new Phrase(tele,textFont));
		     cellmain5.setHorizontalAlignment(Element.ALIGN_RIGHT);
		     cellmain5.setColspan(4);
		     cellmain5.setBorder(Rectangle.NO_BORDER);
		     table.addCell(cellmain5);
		     
		     String time="打印时间:"+df.format(new Date());
		     Cell cellmain2 = new Cell(new Phrase(time,textFont));
		     cellmain2.setHorizontalAlignment(Element.ALIGN_RIGHT);
		     cellmain2.setColspan(4);
		     cellmain2.setBorder(Rectangle.NO_BORDER);
		     table.addCell(cellmain2);
		     //将表格添加到文本中
		     document.add(table);
			// 5.关闭文档
			document.close();
		}catch (Exception e) {
			logger.error("打印系统异常2：",e);
		} finally {
			try{
				if (toClient != null) {
					toClient.close();
				}
				if (fis != null) {
					fis.close();
				}
				if(writer!=null){
					writer.close();
				}
			}catch (Exception e) {
				logger.error("打印系统异常22：",e);
			}
		}
		return filePath;
	}
	private  Cell getCell(String mess,Font typeFont) throws BadElementException {
		 Cell cellleft= new Cell(new Phrase(mess,typeFont));
	     cellleft.setColspan(4);
	     cellleft.setHorizontalAlignment(Element.ALIGN_LEFT);
	     return cellleft;
	}
	
	private  Cell getCellEmty(Font typeFont) throws BadElementException {
		 Cell cellleft= new Cell(new Phrase("",typeFont));
	     cellleft.setColspan(2);
	     cellleft.setHorizontalAlignment(Element.ALIGN_CENTER);
	     return cellleft;
	}
	protected static String replaceStrNULL(String str){
		return str == null || str.isEmpty() ? "" : str;
	}
	
	private String monenyFom(BigDecimal f){
		myformat.applyPattern("##,###.00");
		if(StringUtil.isNotEmpty(String.valueOf(f))){
			return myformat.format(f);
		}else {
			return "0.00";
		}
	}
}
